package idv.arthur.work;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class QueryDevliver extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public QueryDevliver() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = null;
		Connection tarConn = null;
		
		int tarSysNo =	Integer.parseInt(request.getParameter("tarSysNo"));	//提交對象的系統的身份
		
		String deliverSN_q = "".equalsIgnoreCase(request.getParameter("deliverSN_q"))?"":"t1.deliverySN="+ request.getParameter("deliverSN_q")+" AND ";  
		PreparedStatement ps = null;
		ResultSet rs = null;
		String errPars = "}";
		
		
		ArrayList<Struc> strucs = new ArrayList<Struc>();
		final boolean isSU = Boolean.parseBoolean( request.getParameter("isSU") );
		final String currentUser = request.getParameter("userId");
		String subAccess = " t2.subsysid IN(";
		
		String strSQL = null;
		
		
		try {
			conn = wid.getConn(true);
			tarConn = wid.getTarConnection(wid.getLocalSysNo(conn, ps, rs), tarSysNo, conn, ps, rs);		//取得接收方的資料庫連結
			
			if ( isSU ) {
				subAccess = "";
			} else {
				strSQL = "SELECT subsysid FROM mproleuser WHERE userid=? AND roleid=2";
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, currentUser );
				rs = ps.executeQuery();
				while ( rs.next() ) {
					subAccess += "'"+rs.getString("subsysid")+"',";
				}
				subAccess = subAccess.substring(0, subAccess.length()-1);
				subAccess += ") AND ";	
			}
			strSQL = "SELECT t6.subsysname,t2.subsysid,t1.deliverySN,t1.deliveryComment,t1.deliveryTarSN,t1.deplmainSN,t5.username,t2.creator,t2.createdDateTime,t4.statusSN,t4.statusdesc FROM deltask t1,deplmain t2,envsystemlist t2 t3,defdeltask t4,personnel t5,subsys t6 WHERE "+deliverSN_q +"t2.creator=t5.userid AND t6.subsysid=t2.subsysid AND t6.bssid='MBMS' AND t1.isDeliver='t' AND t1.deplmainSN=t2.deplmainSN AND "+subAccess+" t3.sysSN=t1.tarSysSN AND t3.islocalsys='f' AND t1.statusSN=t4.statusSN ORDER BY deliverySN DESC";
			
			ps = tarConn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			while ( rs.next() ) {
				Struc sts = new Struc();
				sts.setSubSysId( rs.getString("subsysid") );
				sts.setSubSysName( wid.DB2UI( rs.getString("subsysname"),conn.getMetaData().getDatabaseProductName() ) );
				sts.setComment( wid.DB2UI( rs.getString("deliveryComment"),conn.getMetaData().getDatabaseProductName() ) );
				sts.setDeliveryTarSN(rs.getInt("deliveryTarSN"));
				sts.setCreator( rs.getString("creator") );
				sts.setCreatedDateTIme(wid.changeTimeFormat(rs.getTimestamp("createdDateTime")));
				sts.setDeplmainSN( rs.getInt("deplmainSN") );
				sts.setStatusdesc( wid.DB2UI( rs.getString("statusdesc"),conn.getMetaData().getDatabaseProductName() ) );
				sts.setDeliverySN( rs.getInt("deliverySN") );
				sts.setCreatorName( wid.DB2UI( rs.getString("username"),conn.getMetaData().getDatabaseProductName() ) );
				sts.setStatusSN( rs.getInt("statusSN") );
				strucs.add(sts);
			}
		} catch ( SQLException e) {
			wid.kem(conn, ps, e, wid.toEType("SQLException")+errPars, wid.isPrint2Console );
		} catch ( UnsupportedEncodingException e) {
			wid.kem(conn, ps, e, wid.toEType("UnsupportedEncodingException")+errPars, wid.isPrint2Console );
		} catch ( Exception e) {
			wid.kem(conn, ps, e, wid.toEType("Exception")+errPars, wid.isPrint2Console );
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
				if (tarConn!= null) {tarConn.close();}
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}
		}
		
		response.getWriter().write(new Gson().toJson(strucs));
	}
}